package com.test.mchelepesa.dialog_rice;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;

import com.test.mchelepesa.R;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;

public class DeleteDataDialog_rice extends Dialog {

    private final Thread countDownThread;
    private Button deleteBtn;
    private final Handler handler;

    @SuppressLint("SetTextI18n")
    public DeleteDataDialog_rice(@NonNull Context context) {
        super(context);
        handler = new Handler(Looper.getMainLooper());
        countDownThread = new Thread(() -> {
            try {
                int count = 10;

                while (count-->0){
                    int finalCount = count;
                    if (isShowing()) handler.post(() -> deleteBtn.setText(context.getString(R.string.confirm)+"("+ finalCount +"s)"));
                    Thread.sleep(999);
                }

                if (isShowing()){
                    handler.post(() -> {
                        deleteBtn.setAlpha(1f);
                        deleteBtn.setText(context.getString(R.string.confirm));
                        deleteBtn.setOnClickListener(v -> {
                            HttpManager_rice.getInstance().saveUserBuriedPoint("DIALOG_DELETE_DATA_DELETE_CLICK");
                            dismiss();
                            HttpManager_rice.getInstance().dropUserData();
                        });
                    });
                }
            }catch (Exception e){
                StringUtil_rice.printException(e);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_delete_data_rice);

        getWindow().setBackgroundDrawableResource(R.color.trans);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        setCanceledOnTouchOutside(false);

        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView(){

        deleteBtn = findViewById(R.id.delete_data_delete);

        findViewById(R.id.delete_data_cancel).setOnClickListener(v -> {
            HttpManager_rice.getInstance().saveUserBuriedPoint("DIALOG_DELETE_DATA_CANCEL_CLICK");
            dismiss();
        });

    }

    @Override
    public void show() {
        super.show();
        countDownThread.start();
    }

}
